import React from 'react';
import { connect } from 'dva';
import { message } from 'antd';
import { ContentPackage, AdvancedSearch, DATA_ENTRY, TableC } from '../../comps';
import { getUserInfo, exportFile } from '../../utils/commonFunc';
import { findTitleByValue } from '../../utils/utils';

class PressureReport extends React.Component {
  constructor() {
    super();
    this.state = {
      columns: [
        {
          key: 'name',
          title: '报告名称',
        },
        {
          key: 'productNum',
          title: '产品数量',
        },
        {
          key: 'templateName',
          title: '模板名称',
        },
        {
          key: 'sceneName',
          title: '情景名称',
        },
        {
          key: 'reportDate',
          title: '报告日期',
        },
        {
          key: 'createDate',
          title: '生成时间',
        },
        {
          key: 'needPenetrate',
          title: '是否穿透',
        },
      ],
      dataSource: [],
      isReset: false, // 是否点击重置
      startDate: '',
      endDate: '',
      lackDate: false, // 日期是否选择季度
    };
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'pressureReportM/getScenes',
      payload: {},
    });
    this.props.dispatch({
      type: 'pressureReportM/getTemplate',
      payload: {},
    });
    //  更新未读消息---用于用户视图数据
    this.props.dispatch({
      type: 'pressureReportM/updateUnreadDate',
      payload: {
        msgType: '4',
      },
    });
    this.getTableData();
  }

  // 改变columns的样式
  changeColumns = (columns) => {
    const { templateList = [], sceneList = [] } = this.props.pressureReportM;
    const data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作') {
        data.push({
          key: 'operate',
          type: 'operate',
          title: '操作',
          width: 100,
          operates: [
            {
              title: '导出',
              onClick: (record, index) => {
                this.export(record);
              },
              rules: {
                disabled: {
                  relation: 'or',
                  items: [
                    {
                      key: 'status',
                      value: ['APPLICATION', 'FAILURE', 'ZUOFEI'],
                      relation: ['=', '=', '='],
                    },
                    {
                      key: 'exportId',
                      value: [null],
                      relation: ['='],
                    },
                  ],
                },
              },
            },
          ],
        });
      }
      data.map((item) => {
        if (item.key == 'name') {
          item.width = '30%';
        }
        if (item.key == 'status') {
          item.width = 80;
          item.render = (text) => {
            if (text === 'SUCCESS') {
              return '已确认';
            } else {
              return '--';
            }
          };
        }
        if (item.key == 'productNum') {
          item.align = 'right';
          item.width = 100;
        }
        if (item.key == 'createDate') {
          item.align = 'right';
          item.width = 160;
        }
        if (item.key == 'reportDate') {
          item.width = 100;
          item.type = 'date';
        }
        if (item.key == 'sceneName' || item.key == 'templateName') {
          // 情景名称 模板名称 maat需要手动翻译
          item.width = 100;
          item.render = (text, record) => {
            return findTitleByValue(text, item.key == 'sceneName' ? sceneList : templateList) || '--';
          };
        }
        if (item.key == 'needPenetrate') {
          item.width = 80;
          item.render = (text) => {
            if (text === null || text === undefined) {
              return '--';
            } else {
              return text == 1 ? '是' : '否';
            }
          };
        }
      });
    }
    return data;
  };

  // 导出文件
  export = (e) => {
    // 2022-07-05需求调整
    // 当前逻辑：在2022年第一季度出具的压测报告是以生成好放到指定目录的方式下载的---压力测试报告(下载)页面，之后的压测报告是需要用户点击“导出”时，后台再生成，生成完毕再返回文件的形式---压力测试报告页面
    // 客户需求：用户想要在列表中看到所有在Maat平台上下载过的报告列表，所以这边仅针对2022年第一季度下载过报告的租户进行特殊处理。
    // 处理方法：对压测页面表格数据中2022-03-31的数据使用压力测试报告(下载)页面方法导出，即：当数据是2022-03-31的获取压测报告生成好的指定目录进行导出
    message.info('报告正在导出，请勿重新点击！');
    exportFile('gateway/file/maat-admin/file/download', { uniquekey: e.exportId });
    // if (e.reportDate && e.reportDate.includes('2022-03-31')) {
    //   this.props.dispatch({
    //     type: 'pressureReportM/queryList',
    //     payload: { fileType: '压力测试' },
    //     callback: (data) => {
    //       if (data && data.dataSource && data.dataSource.length) {
    //         const file = data.dataSource.filter((item) => !item.tenantName || item.tenantName === e.managerName);
    //         if (file.length) {
    //           exportFile('gateway/maat-risk/stress-test-report/download', { uniquekey: file[0]?.fileId });
    //         } else {
    //           exportFile('gateway/maat-risk/stress-test-report/download', { reportId: e.id});
    //         }
    //       }
    //     },
    //   });
    // } else {
    //   exportFile('gateway/maat-workstation/stress-test-report/download', { reportId: e.id, reportType: e.reportType });
    // }
  };

  // 原到处功能
  originalExport = (e) => {
    message.info('报告正在导出，请勿重新点击！');
    if (e.reportType === '0') {
      // maat上传的 导出
      exportFile('gateway/file/maat-admin/file/download', { uniquekey: e.id });
      return;
    }
    // evar系统
    fetch(`/maat/api/evar/api/stress-test-report/get-word-report?reportId=${e.id}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/octet-stream;charset=UTF-8',
        'maat-user': 'EVAR_maat&PressureTest123!!',
      },
      responseType: 'blob', // blob获取二进制流
    })
      .then((response) => {
        return response.blob();
      })
      .then((res) => {
        const a = document.createElement('a');
        const body = document.querySelector('body');
        const bl = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
        a.download = `${e.name}.docx`;
        a.href = window.URL.createObjectURL(bl);
        a.style.display = 'none';
        body.appendChild(a);
        a.click();
        body.removeChild(a);
        window.URL.revokeObjectURL(a.href);
      });
  };

  // 查询
  onQuery = (e) => {
    if (this.state.lackDate) {
      message.warning('请选择季度');
      return;
    }
    this.setState(
      {
        isReset: false, // 是否点击重置
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 重置
  onClear = () => {
    this.setState({
      isReset: true,
      startDate: '',
      endDate: '',
      lackDate: false,
    });
  };

  // 获取表格数据
  getTableData = () => {
    this.setState(
      {
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'stressTestReportConfirmM/getDataList',
          payload: {
            startDate: this.state.startDate,
            endDate: this.state.endDate,
            currentPage: 1,
            numInPage: 99999,
            managerName: getUserInfo().tenantCHNname ? getUserInfo().tenantCHNname : '',
            tenant: getUserInfo().tenantName || '',
            statusList: ['SUCCESS'],
          },
          callback: (data) => {
            this.setState({
              dataSource: data.dataSource,
            });
          },
        });
      },
    );
  };

  render() {
    const { columns, dataSource } = this.state;
    const { loading } = this.props;
    const dataSourceQuery = [
      {
        yearKey: 'year',
        quarterKey: 'quarter',
        type: DATA_ENTRY.SIMPLEQUARTERC,
        title: '报告时间',
        highCurrentDate: true,
        onQuarterChange: (data) => {
          this.setState({
            startDate: data.beginDate,
            endDate: data.endDate,
            lackDate: !!data.lackDate,
          });
        },
      },
    ];
    const newColumns = this.changeColumns(columns);
    return (
      <ContentPackage
        title='压力测试报告'
        contentHtml={
          <div>
            <div>
              <AdvancedSearch dataSource={dataSourceQuery} onQuery={this.onQuery} onClear={this.onClear} />
              <div style={{ marginTop: '16px' }}>
                <TableC
                  columns={newColumns}
                  dataSource={dataSource}
                  rowKey='id'
                  selfScrollY={true}
                  onChange={this.handleTableChange}
                  hidePage={true}
                  loading={loading.effects['pressureReportM/getDataList']}
                />
              </div>
            </div>
          </div>
        }
      />
    );
  }
}
export default connect(({ pressureReportM, loading, stressTestReportConfirmM }) => ({ pressureReportM, loading, stressTestReportConfirmM }))(PressureReport);
